#!/usr/bin/python

import base64
from socket import *
import getopt
import urllib2
import sys

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'd:u:p:v')
    except getopt.GetoptError:
        usage()
        sys.exit(2)
        
    verbose = False
    domain = None
    username = None
    passwordarg = None
    
    for o,a in opts:
        if o == '-d':
            domain = a
        elif o == '-u':
            username = a
        elif o == '-p':
            passwordarg = a
        elif o == '-v':
            verbose = True
    
    exitcode = 0
    if domain == None or username == None or passwordarg == None:
        usage()
        sys.exit(3)    
    
    resolvedip = gethostbyname(domain)
    try:
        realip = urllib2.urlopen('http://whatismyip.org').read()
    except:
        print 'Unable to get current IP'
        sys.exit(4)
        
    if realip.split()[0] == 'Error:':
        print 'Please set update to only run once every 10 minutes'
        sys.exit(3)
             
    if verbose:
        print 'Old entry: ' + resolvedip
        print 'New entry: ' + realip
    
    if resolvedip != realip:
        if verbose:
            print 'Updating DNS'
        mysocket = socket(AF_INET, SOCK_STREAM)
        mysocket.connect(('dyn.everydns.net',80))
        
        url = '/index.php?ver=0.1&ip=' + realip + '&domain=' + domain
        version = '0.1'
        target = 'dyn.everydns.net'
        password = base64.b64encode(username + ':' + passwordarg)
        
        mysocket.send('GET ' + url + ' HTTP/1.0\r\n');
        mysocket.send('User-Agent: eDNS.pl ' + version + '\r\n');
        mysocket.send('Host: ' + target + '\r\n');
        mysocket.send('Authorization: Basic ' + password + '\r\n\r\n')
        
        while 1:
            data = mysocket.recv(1024)
            if not data: break 
            if verbose:
                print data
        
        mysocket.close()
    else:
        if verbose:
            print 'DNS info already up-to-date'

def usage():
    print 'usage: DNSUpdate -d domain -u username -p password [-v]'
    print ''
    print '       -v is for verbose output'
        
if __name__ == "__main__":
    main()